import { AssetManager, isValid, Node, Sprite, SpriteAtlas, SpriteFrame } from "cc";
import { ResMgr } from "../mgr/ResMgr";



export class RenderUtil {

    constructor(
        public resMgr: ResMgr
    ) {

    }

    /**
     * 设置单张图的spriteFrame
     * @param sp 
     * @param path 
     */
    setSp(sprite: Sprite, path: string): void {
        const [vId, bundleName, resName] = path.split("#");
        const viewId = Number(vId);
        this.resMgr.loadBundle(viewId, bundleName).then((bundle: AssetManager.Bundle) => {
            this.resMgr.loadSinglePicResByBundle(bundleName, `${resName}/spriteFrame`).then((sp: SpriteFrame) => {
                if (isValid(sprite)) {
                    sprite.spriteFrame = sp;
                }
            })
        })
    }

    /**
     * 设置图集的spriteFrame
     * @param sp 
     * @param path 
     */
    setSpAtlas(sp: Sprite, path: string): void {
        const [vId, bundleName, atlasName, resName] = path.split("#");
        const viewId = Number(vId);
        this.resMgr.loadBundle(viewId, bundleName).then(() => {
            this.resMgr.loadAtlasByBundle(bundleName, atlasName).then((atlasAsset: SpriteAtlas) => {
                if (isValid(sp)) {
                    sp.spriteFrame = atlasAsset.getSpriteFrame(resName);
                }
            })
        })
    }


    searchChild(node: Node, name: string) {
        let ret = node.getChildByName(name);
        if (ret) return ret;
        for (let i = 0; i < node.children.length; i++) {
            let child = node.children[i];
            if (!child.isValid) continue;
            ret = this.searchChild(child, name);
            if (ret) return ret;
        }
        return null;
    }

}